package org.example.service.mqtt.impl;

import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.example.common.handle.MqttServiceHandle;
import org.example.service.mqtt.MqttService;
import org.example.service.mqtt.TopicService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.List;

/**
 * @Author 李荣
 * @Date 2025/1/3
 * @Description
 */

@Service
public class MqttServiceImpl implements MqttService {

    private final MqttClient mqttClient;

    private final MqttServiceHandle mqttServiceHandle;

    private final TopicService topicService;

    @Autowired
    public MqttServiceImpl(MqttClient mqttClient,MqttServiceHandle mqttServiceHandle,TopicService topicService)
    {
        this.mqttClient = mqttClient;
        this.mqttServiceHandle = mqttServiceHandle;
        this.topicService = topicService;
    }

    @PostConstruct
    void init()
    {
        try
        {
            connect();
            mqttClient.setCallback(mqttServiceHandle);
            List<String> topicsToSubscribe = topicService.getTopicsToSubscribe();
            for (String topic : topicsToSubscribe) {
                mqttClient.subscribe(topic);
            }
        }catch (Exception e)
        {
            e.printStackTrace();
        }
    }
    @Override
    public void connect() throws MqttException {
        if (mqttClient.isConnected())
        {
            return;
        }
        mqttClient.connect();
    }

    @Override
    public void disconnect() throws MqttException {
        mqttClient.disconnect();
    }

    @Override
    public void subscribe(String topic) throws MqttException {
        mqttClient.subscribe(topic);
    }

    @Override
        public void publish(String topic, MqttMessage message) throws MqttException {
        mqttClient.publish(topic,message);

    }

    @Override
    public void close() throws MqttException {
        mqttClient.close();
    }
}
